import { View, Text, ScrollView, Image } from '@tarojs/components'
import { useState, useEffect } from 'react'
import Taro from '@tarojs/taro'
import { API_BASE_URL } from '../../../config/env'

const DoctorCard = ({ doctor, onClick }) => {
  const [avatarLoaded, setAvatarLoaded] = useState(false)
  const [avatarError, setAvatarError] = useState(false)
  const [avatarRetryCount, setAvatarRetryCount] = useState(0)
  const [productImagesLoaded, setProductImagesLoaded] = useState({})
  const [productImagesError, setProductImagesError] = useState({})
  const [productImagesRetryCount, setProductImagesRetryCount] = useState({})
  const maxRetries = 2 // 最多重试2次

  // 备用图片URL
  const fallbackAvatar = 'https://images.unsplash.com/photo-1559839734-2b71ea197ec2?w=100&h=100&fit=crop&crop=face'
  const fallbackProductImage = 'https://images.unsplash.com/photo-1559757148-5c350d0d3c56?w=300&h=200&fit=crop'
  
  // 处理图片URL，将相对路径转换为完整URL
  const getFullImageUrl = (imageUrl) => {
    if (!imageUrl) return fallbackAvatar
    if (imageUrl.startsWith('http')) return imageUrl
    if (imageUrl.startsWith('/')) return `${API_BASE_URL}${imageUrl}`
    return `${API_BASE_URL}/${imageUrl}`
  }

  // 重置头像加载状态
  useEffect(() => {
    setAvatarLoaded(false)
    setAvatarError(false)
  }, [doctor.avatar])

  const handleAvatarLoad = () => {
    setAvatarLoaded(true)
    setAvatarError(false)
    console.log('医生头像加载成功:', doctor.avatar)
  }

  const handleAvatarError = () => {
    const newRetryCount = avatarRetryCount + 1
    setAvatarRetryCount(newRetryCount)
    
    if (newRetryCount >= maxRetries) {
      setAvatarError(true)
      setAvatarLoaded(false)
      console.log(`医生头像加载失败，已重试${newRetryCount}次，停止重试:`, doctor.avatar)
    } else {
      console.log(`医生头像加载失败，第${newRetryCount}次重试:`, doctor.avatar)
      // 延迟重试
      setTimeout(() => {
        setAvatarError(false)
        setAvatarLoaded(false)
      }, 1000)
    }
  }

  const handleProductImageLoad = (productId) => {
    setProductImagesLoaded(prev => ({ ...prev, [productId]: true }))
    setProductImagesError(prev => ({ ...prev, [productId]: false }))
    console.log('医生产品图片加载成功:', productId, '图片URL:', doctor.products.find(p => p.id === productId)?.image)
  }

  const handleProductImageError = (productId, originalUrl) => {
    const currentRetryCount = productImagesRetryCount[productId] || 0
    const newRetryCount = currentRetryCount + 1
    setProductImagesRetryCount(prev => ({ ...prev, [productId]: newRetryCount }))
    
    if (newRetryCount >= maxRetries) {
      setProductImagesError(prev => ({ ...prev, [productId]: true }))
      setProductImagesLoaded(prev => ({ ...prev, [productId]: false }))
      console.log(`医生产品图片加载失败，已重试${newRetryCount}次，停止重试:`, productId, '原始URL:', originalUrl)
    } else {
      console.log(`医生产品图片加载失败，第${newRetryCount}次重试:`, productId, '原始URL:', originalUrl)
      // 延迟重试
      setTimeout(() => {
        setProductImagesError(prev => ({ ...prev, [productId]: false }))
        setProductImagesLoaded(prev => ({ ...prev, [productId]: false }))
      }, 1000)
    }
  }

  const handleClick = () => {
    if (onClick) {
      onClick(doctor)
    }
  }

  // 处理咨询按钮点击
  const handleConsultClick = (e) => {
    if (e && typeof e.stopPropagation === 'function') {
      e.stopPropagation()
    }
    // 跳转到聊天页，携带医生信息
    const doctorId = doctor.id || doctor._id || ''
    const doctorName = encodeURIComponent(doctor.name || '')
    const query = `?targetType=doctor&targetId=${doctorId}&targetName=${doctorName}`
    console.log('doctor consult tap -> navigateTo', `/pages/chat/chat${query}`)
    Taro.navigateTo({ url: `/pages/chat/chat${query}` })
      .catch(() => {
        Taro.showToast({
          title: '无法打开聊天页',
          icon: 'none'
        })
      })
  }

  return (
    <View className='doctor-card' onClick={handleClick}>
      {/* 医生头部信息 */}
      <View className='doctor-header'>
        <View className='doctor-info'>
          <View className='avatar-container'>
            {!avatarLoaded && !avatarError && (
              <View className='avatar-loading'>
                <Text>加载中...</Text>
              </View>
            )}
            {!avatarError ? (
              <Image 
                className={`doctor-avatar ${avatarLoaded ? 'loaded' : ''}`}
                src={getFullImageUrl(doctor.avatar)}
                mode='aspectFill'
                onLoad={handleAvatarLoad}
                onError={handleAvatarError}
                lazyLoad
              />
            ) : (
              <View className='avatar-placeholder'>
                <View className='placeholder-icon'>👨‍⚕️</View>
                <View className='placeholder-text'>医生</View>
              </View>
            )}
          </View>
          <View className='doctor-details'>
            <Text className='doctor-name'>{doctor.name} {doctor.hospital}</Text>
            <View className='doctor-specialties'>
              {doctor.specialties && doctor.specialties.length > 0 ? (
                doctor.specialties.map((specialty, index) => (
                  <View key={index} className='specialty-tag'>
                    <Text>{specialty}</Text>
                  </View>
                ))
              ) : (
                <View className='no-specialties'>
                  <Text>暂无专业信息</Text>
                </View>
              )}
            </View>
          </View>
        </View>
        <View className='doctor-actions'>
          <View className='consult-btn' onClick={handleConsultClick}>私信咨询</View>
        </View>
      </View>
      
      {/* 医生标签 */}
      <View className='doctor-tag'>
        <Text>{doctor.tag}</Text>
      </View>
      
      {/* 医生产品列表 - 水平滚动 */}
      <View className='doctor-products-container'>
        {doctor.products && doctor.products.length > 0 ? (
          <ScrollView 
            className='doctor-products-scroll'
            scrollX
            showScrollbar={false}
            enhanced
            scrollWithAnimation
          >
            <View className='doctor-products-list'>
              {doctor.products.map((product) => {
                const productId = product.id || product._id
                const isImageLoaded = productImagesLoaded[productId]
                const isImageError = productImagesError[productId]
                
                return (
                  <View key={productId} className='doctor-product-card'>
                    <View className='product-image-container'>
                      {!isImageLoaded && !isImageError && (
                        <View className='product-image-loading'>
                          <Text>加载中...</Text>
                        </View>
                      )}
                      <Image 
                        className={`product-image ${isImageLoaded ? 'loaded' : ''}`}
                        src={isImageError ? fallbackProductImage : getFullImageUrl(product.image)}
                        mode='aspectFill'
                        onLoad={() => handleProductImageLoad(productId)}
                        onError={() => handleProductImageError(productId, product.image)}
                        lazyLoad
                      />
                    </View>
                    <Text className='product-title'>{product.title}</Text>
                    <View className='product-price'>
                      <Text className='current-price'>¥{product.price}</Text>
                      {product.saved > 0 && <Text className='saved-price'>已省¥{product.saved}</Text>}
                    </View>
                  </View>
                )
              })}
            </View>
          </ScrollView>
        ) : (
          <View className='no-products'>
            <Text>暂无产品信息</Text>
          </View>
        )}
      </View>
    </View>
  )
}

export default DoctorCard
